package com.mua.test.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mua.test.common.Result;
import com.mua.test.config.JwtService;
import com.mua.test.user.dto.LoginRequest;
import com.mua.test.user.entity.User;
import com.mua.test.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * 注册，登陆，验证码之类
 * @author JiangLan
 * @since 2024/4/22 14:02
 */
@Slf4j
@RequestMapping("/api/auth")
@RestController
public class AuthController {
    @Resource
    private JwtService jwtService;
    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequest.getUsername());
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException("用户名错误");
        }
        if(!user.getEnabled()){
            throw new RuntimeException("该用户已禁用");
        }
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        String token = jwtService.generateToken(user.getUsername());
        // todo 将token和用户信息存到redis
        return Result.success(token, "登陆成功");
    }

    @PostMapping("/logout")
    public Result logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
            // todo 删除redis的token缓存
        }
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        return Result.success(user.getUsername() + "登出成功");
    }

    @PostMapping("/hello")
    public String hello(@RequestBody LoginRequest loginRequest, HttpServletRequest request){
        return "hello";
    }
}
